package top.psjj.mall.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import top.psjj.mall.comment.Constant;
import top.psjj.mall.comment.Result;
import top.psjj.mall.exception.MallExceptionEnum;
import top.psjj.mall.model.po.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AdminFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取session
        HttpSession session = request.getSession();
        //设置响应格式
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        //获取用户信息
        User user = (User)session.getAttribute(Constant.User.CURRENT_USER);
        //如果没登陆
        if(user==null){
            Result error = Result.error(MallExceptionEnum.NEED_LOGIN);
            String resultJson = objectMapper.writeValueAsString(error);
            response.getWriter().write(resultJson);
            return;
        }
        //登陆判断角色
        if(user.getRole().equals(Constant.User.IS_ADMIN)){
            //符合角色放行
            filterChain.doFilter(request,response);
        } else {
            Result error = Result.error(MallExceptionEnum.NEED_ADMIN);
            String resultJson = objectMapper.writeValueAsString(error);
            response.getWriter().write(resultJson);
        }
    }
}
